package org.examples;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.ConnectionPool;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.MultipartReader;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import lombok.extern.slf4j.Slf4j;

import static org.examples.DebugConstants.vocsInputJson;
import static org.examples.DebugConstants.vocsParametersJson;

@Slf4j
public class OkVocs {
  public static void main(final String[] args) throws Exception {
    ExecutorService executorService = Executors.newFixedThreadPool(5);
    OkHttpClient client = new OkHttpClient.Builder()
//        .connectTimeout(10, TimeUnit.SECONDS)
//        .writeTimeout(10, TimeUnit.SECONDS)
//        .readTimeout(30, TimeUnit.SECONDS)
//        .connectionPool(new ConnectionPool(5, 30L, TimeUnit.SECONDS))
        .build();


    RequestBody requestBody = new MultipartBody.Builder()
        .addFormDataPart("Parameters", null, RequestBody.create(vocsParametersJson,MediaType.parse("application/json")))
        .addFormDataPart("Input", null, RequestBody.create(vocsInputJson,MediaType.parse("application/json")))
        .setType(MediaType.parse("multipart/form-data"))
        .build();

    Request postRequest = new Request.Builder()
        .url("http://10.192.128.28:28166/vocs/speak")
        .header("Content-Type","multipart/form-data")
        .post(requestBody)
        .build();

    long t1 = System.currentTimeMillis();
    final CountDownLatch latch = new CountDownLatch(1);

    client.newCall(postRequest).enqueue(new Callback() {
      @Override
      public void onFailure(@NotNull Call call, @NotNull IOException e) {
        System.out.println("-----------onFailure-----");
        e.printStackTrace();
        latch.countDown();
      }

      @Override
      public void onResponse(@NotNull Call call, @NotNull Response response) {
        System.out.println("-----------onResponse-----");
        //System.out.println(response.body().string());
        response(response, t1,latch);
//        latch.countDown();
      }
    });
    try{
      latch.wait( );
    }catch (Exception e){
      log.error(e.getMessage());
    }
    client.dispatcher().executorService().shutdown();
    System.out.println("------------done---------------");
//    try {
//      Thread.sleep(20000);
//    } catch (InterruptedException e) {
//      e.printStackTrace();
//    }
  }

  public static void response(Response response, long startTime,CountDownLatch latch) {
    MultipartReader reader = null;
    try {
      reader = new MultipartReader(response.body());
      while (true) {
//        log.info("while (true) ");
        MultipartReader.Part part = reader.nextPart();
        if (part == null) {
          break;
        }
        System.out.println(getPartName(part.headers()));
        if ((part.headers().toString().indexOf("name=\"AudioInfo\"")!=-1)) {
          System.out.println("0000000000000000000");
        }

        if (part.headers().toString().contains("Audio")) {
          System.out.println("================"+ (System.currentTimeMillis() - startTime));
        }
        byte[] bytes = part.body().readByteArray();
        System.out.println(part.headers());
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    latch.countDown();

  }

  private static String getPartName(Headers headers) {
    String disposition = headers.get("Content-Disposition");
    if (StringUtils.isNoneBlank(disposition)) {
      for (String keyValue : disposition.split(";")) {
        if (keyValue.contains("name=")) {
          return keyValue.split("=")[1];
        }
      }
    }
    return null;
  }
}
